#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/sendfile.h>
#include "test.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#define BLOG_FILE_NAME "../../blog.txt"
#define BUFFER_LEN 2048

off_t get_file_size(const char *filename)
{
    struct stat st;
    if (stat(filename, &st) == -1)
    {
        return 0;
    }
    return st.st_size;
}

int connect_tcpserver(const char *ip, unsigned short port);

int send_msg(int connfd, char *msg, int length)
{

    int res = send(connfd, msg, length, 0);
    if (res < 0)
    {
        perror("send");
        exit(1);
    }
    return res;
}

int recv_msg(int connfd, char *msg, int length)
{

    int res = recv(connfd, msg, length, 0);
    // LOG("res: %s\n", msg);
    if (res < 0)
    {
        perror("recv");
        exit(1);
    }
    //LOG("recv_len: %d\n", res);

    return res;
}

int connect_tcpserver(const char *ip, unsigned short port)
{

    int connfd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in tcpserver_addr;
    memset(&tcpserver_addr, 0, sizeof(struct sockaddr_in));

    tcpserver_addr.sin_family = AF_INET;
    tcpserver_addr.sin_addr.s_addr = inet_addr(ip);
    tcpserver_addr.sin_port = htons(port);

    int ret = connect(connfd, (struct sockaddr *)&tcpserver_addr, sizeof(struct sockaddr_in));
    if (ret)
    {
        perror("connect");
        return -1;
    }

    return connfd;
}

#define TEST_IP "192.168.248.1"
#define TEST_PORT 8080

// ./test_set
int main(int argc, char *argv[])
{
    int connfd = connect_tcpserver(IP, PORT);

    // int connfd = connect_tcpserver(TEST_IP, TEST_PORT);
    if (send_msg(connfd, "RGET blog\x03", strlen("RGET blog\x03")) != strlen("RSET blog\x03"))
    {
        close(connfd);
        LOG("fail\n");
        return -1;
    }
    off_t file_size = get_file_size(BLOG_FILE_NAME);

    int file_fd = open(BLOG_FILE_NAME, O_RDONLY);

    char buffer[BUFFER_LEN + 1] = {0};
    char file_buffer[BUFFER_LEN + 1] = {0};

    off_t total_recv = 0;

    while (total_recv != file_size)
    {
        int ret = recv_msg(connfd, buffer, BUFFER_LEN);
        if (ret <= 0)
        {
            close(connfd);
            LOG("fail\n");
            return -1;
        }
        buffer[ret] = '\0';
        int res = read(file_fd, file_buffer, ret);
        file_buffer[res] = '\0';
        if (strcmp(buffer, file_buffer) != 0)
        {
            close(connfd);
            LOG("fail\n");
            return -1;
        }
        total_recv += ret;
        printf("%s", buffer);
        
    }
    printf("\n");

    close(connfd);
    LOG("success get blog: %ld bytes\n", file_size);

    return 0;
}
